package cn.org.tpeach.nosql.controller;

import cn.org.tpeach.nosql.bean.DicBean;
import cn.org.tpeach.nosql.constant.RedisInfoKeyConstant;
import cn.org.tpeach.nosql.framework.LarkFrame;
import cn.org.tpeach.nosql.framework.ServiceProxy;
import cn.org.tpeach.nosql.redis.bean.RedisTreeItem;
import cn.org.tpeach.nosql.redis.bean.SlowLogBo;
import cn.org.tpeach.nosql.redis.service.IRedisConnectService;
import cn.org.tpeach.nosql.tools.DataStructureUtils;
import cn.org.tpeach.nosql.tools.DateTools;
import cn.org.tpeach.nosql.tools.StringUtils;
import cn.org.tpeach.nosql.view.JavaFxUtil;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import lombok.Getter;

import java.awt.*;
import java.io.Closeable;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author tyz
 * @Title: ServerinfoTextController
 * @ProjectName Redis-Lettuce-Parent
 * @Description: TODO
 * @date 2020-06-06 22:30
 * @since 2.0.0
 */
@Getter
public class ServerInfoController implements Initializable, Closeable {
    IRedisConnectService redisConnectService = ServiceProxy.getBeanProxy("redisConnectService", IRedisConnectService.class);
    @FXML
    private BorderPane serverInfoBorderPane;

    @FXML
    private Text infoRedisVersionText;
    @FXML
    private Text infoOsText;
    @FXML
    private Text infoProcessIdText;
    @FXML
    private Text infoRedisModeText;
    @FXML
    private Text infoPortText;
    @FXML
    private Text infoUptimeInSecondsText;
    @FXML
    private Text infoUsedMemoryHumenText;
    @FXML
    private Text infoUsedMemoryPeakHumanText;
    @FXML
    private Text infoUsedMemoryRssHumenText;
    @FXML
    private Text infoMemFragmentationRatioText;
    @FXML
    private Text infoMemAllocatorText;
    @FXML
    private Text infoTotalConnectionsReceivedText;
    @FXML
    private Text infoTotalCommandsProcessedText;
    @FXML
    private Text infoInstantaneousOpsOerSecText;
    @FXML
    private Text infoTotalNetInputBytesText;
    @FXML
    private Text infoTotalNetOutputBytesText;
    @FXML
    private Text infoRejectedConnectionsText;
    @FXML
    private Text infoConnectedClientsText;
    @FXML
    private Text infoClientLongestOutputListText;
    @FXML
    private Text infoClientBiggestInputBufText;
    @FXML
    private Text infoBlockedClientsText;
    @FXML
    private Text infousedCpuSysText;
    @FXML
    private Text infoUsedCpuUserText;
    @FXML
    private Text infoUsedCpuSysChildrenText;
    @FXML
    private Text infoUsedCpuUserChildrenText;

    @FXML
    private TableView<SlowLogBo> slowLogTabelView;
    @FXML
    TableColumn<SlowLogBo,String> slowLogIdCol;
    @FXML
    TableColumn<SlowLogBo,String> slowLogCmdCol;
    @FXML
    TableColumn<SlowLogBo,String> slowLogProcessAtCol;
    @FXML
    TableColumn<SlowLogBo,String> slowLogExecTimeCol;

    @FXML
    private TableView<DicBean> infoAllTableView;
    @FXML
    TableColumn<DicBean,String> infoAllKeyCol;
    @FXML
    TableColumn<DicBean,String> infoAllValueCol;

    @FXML
    private RadioButton infoAutoRefreshRadio;
    @FXML
    private Button serverRefreshButton;
    private TreeItem<RedisTreeItem> selectedItem;
    private Tab tab;
    private Future<?> future;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        slowLogIdCol.setCellValueFactory(param -> new SimpleStringProperty(StringUtils.decimalFormat.format(param.getValue().getId())));
        slowLogProcessAtCol.setCellValueFactory(param -> new SimpleStringProperty(StringUtils.decimalFormat.format(param.getValue().getOperTime())));
        slowLogExecTimeCol.setCellValueFactory(param -> new SimpleStringProperty(StringUtils.decimalFormat.format(param.getValue().getExcuteTime())));
        slowLogCmdCol.setCellValueFactory(new PropertyValueFactory<>("cmd"));
        infoAllKeyCol.setCellValueFactory(new PropertyValueFactory<>("code"));
        infoAllValueCol.setCellValueFactory(new PropertyValueFactory<>("value"));
        serverRefreshButton.setGraphic(new ImageView("/view/img/whiteRefresh.png"));
    }

    public void initialize(TreeItem<RedisTreeItem> selectedItem, Tab tab) {
        this.selectedItem = selectedItem;
        this.tab = tab;
        updateUI();
        //启动定时任务
        future = LarkFrame.executorService.scheduleAtFixedRate(() -> {
            if(infoAutoRefreshRadio.isSelected()){
                Platform.runLater(()->updateUI());
            }
        }, 5, 5, TimeUnit.SECONDS);
    }
    @FXML
    public void updateUI() {
        RedisTreeItem value = selectedItem.getValue();
        Map<String, String> redisinfoTextMap = redisConnectService.getConnectInfo(value.getId(), true, false);
//        List<RedisClientBo> redisClientList = redisConnectService.clientList(value.getId(), false);
        List<SlowLogBo> slowLogList = redisConnectService.slowlogGet(value.getId(), false);
        infoRedisVersionText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.redisVersion));
        infoOsText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.OS));
        infoProcessIdText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.processId));
        infoRedisModeText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.redisMode));
        infoPortText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.tcpPort));
        infoUptimeInSecondsText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.uptimeInSeconds));

        infoUsedMemoryHumenText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedMemoryHuman));
        infoUsedMemoryPeakHumanText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedMemoryPeakHuman));
        infoUsedMemoryRssHumenText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedMemoryRssHuman));
        infoMemFragmentationRatioText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.memFragmentationRatio));
        infoMemAllocatorText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.memAllocator));

        infoTotalConnectionsReceivedText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.totalConnectionsReceived));
        infoTotalCommandsProcessedText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.totalCommandsProcessed));
        infoInstantaneousOpsOerSecText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.instantaneousOpsOerSec));
        infoTotalNetInputBytesText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.totalNetInputBytes));
        infoTotalNetOutputBytesText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.totalNetOutputBytes));
        infoRejectedConnectionsText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.rejectedConnections));

        infoConnectedClientsText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.connectedClients));
        infoClientLongestOutputListText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.clientLongestOutputList));
        infoClientBiggestInputBufText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.clientBiggestInputBuf));
        infoBlockedClientsText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.blockedClients));

        infousedCpuSysText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedCpuSys));
        infoUsedCpuUserText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedCpuUser));
        infoUsedCpuSysChildrenText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedCpuSysChildren));
        infoUsedCpuUserChildrenText.setText(redisinfoTextMap.get(RedisInfoKeyConstant.usedCpuUserChildren));

        if(DataStructureUtils.isNotEmpty(slowLogList)){
            slowLogTabelView.setItems(FXCollections.observableArrayList(slowLogList));
        }else if(DataStructureUtils.isNotEmpty(slowLogTabelView.getItems())){
            slowLogTabelView.getItems().clear();
        }
        if(DataStructureUtils.isNotEmpty(redisinfoTextMap)){
            List<DicBean> beanList = redisinfoTextMap.entrySet().stream().map(entry -> new DicBean(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            infoAllTableView.setItems(FXCollections.observableArrayList(beanList));
        }
        infoAllTableView.refresh();
        slowLogTabelView.refresh();

    }

    public void updateUI(TreeItem<RedisTreeItem> selectedItem) {
        this.selectedItem = selectedItem;
        updateUI();
    }

    @Override
    public void close() {
        this.tab = null;
        this.selectedItem = null;
        future.cancel(true);
    }





}
